// 把生成命名空间的方法绑定在jQuery上 
var $BaiduMap = {};
/**
 * option  地图参数 begin----------------
 * 			mapId 地图id  存放地图容易id
 * 			LatLng {latitude:30.503491848938236,longitude:114.33935165405273}中心点经纬度   地图设置中心经纬度
 * 			zoom	设置地图缩放级别  默认缩放级别为10
 * 			maxZoom 设置地图最大级别	默认最大级别纬2
 * 			
 * marker	标记参数  对标记物进行操作的参数
 * 			markDraggable 是否启动拖拽
 * 			markerData	存放标记物数组 [{latitude:30.503491848938236,longitude:114.33935165405273}].
 * 			markListenerFlag 是否对marker进行监听   true则对每个覆盖物给单击弹窗提示
 * 			markerClustererFlag 是否需要聚合	true需要聚合。目前户用型根据省来聚合需要从后台获取数据
 * 			textBegin 聚合 文字描述拼接	聚合时图标文字提示拼接
 * 			textEnd 聚合 文字描述拼接
 * 			customMarkerFlag 自定义图标	是否使用自定义图标，默认使用官方图标
 * 			markerClustererGroup 保存国家、省、市下电站的值。是个数组
 * 				markerClustererGroup中属性{
 * 											minZoom:5,maxZoom:4 设置地图在4-5层级展示这个数组的数据
 * 											markerClustererData  存放该地图缩放等级标记物数组
 * 											clustField   取markerClustererData数组中的字段属性
 * 											countField	取markerClustererData数组中的字段值
 * 											labelText	地图标志物开头
 * 											labelTextMiddle	地图标志物文字中间拼接
 * 											labelTextEnd	地图标志物文字拼接结尾
 * 										}	
 * clustField、countField、labelText、labelTextMiddle、labelTextEnd组合使用文字提示信息为
 * labelText+markerClustererData[i].clustField+labelTextMiddle+markerClustererData[i].countField+labelTextEnd
 * eg:提示文本  <br/>咸宁市<br/>电站共有45个
 */
$BaiduMap.BaiduMapPlugin = function(options,markerCtrl,HomeControl,other){
	this.baiduCore = {};// 创建google基础对象
	this.options_ = options;//地图参数
	this.markerCtrl_ = markerCtrl;//marker参数
	this.map_ = null;//地图实例
	this.markerClusterer_ = null;//聚合类
	this.HomeControl_ = HomeControl;//工具类参数
	this.click_lis ={};//监听工具的事件
	this.overlays = [];//用于储存marker 用于删除地图上marker 新增mark时使用
	this.other_ = other;//其他信息
	
	//初始化地图
	this.initBaiduMap = function(){
		this.map_ = new BMap.Map(this.options_.mapId);            // 创建Map实例latitude:51.6180165488,longitude:62.2705078125
		if( $("#center_longitude").val() && $("#center_latitude").val()){
			var latlng = {latitude:$("#center_latitude").val(),longitude:$("#center_longitude").val()}
			$("#center_longitude,#center_latitude").val('');//清空中心经纬度
			this.options_.geolocationFlag=false;
		}else{
			var latlng = this.options_.LatLng||{latitude:30.503491848938236,longitude:114.33935165405273};
			if(!this.options_.LatLng){
				this.options_.geolocationFlag = true;
			}
		}
		//获取定位中心点
		if(this.options_.geolocationFlag){
			this.getLocalCityPoint();
		}else{
			var point = new BMap.Point(latlng.longitude,latlng.latitude);//准备设置地图中心点
			this.map_.centerAndZoom(point,this.options_.zoom||6);
		}
		this.map_.setMinZoom(this.options_.maxZoom||2);
		this.map_.setMaxZoom(this.options_.minZoom||15);
		this.map_.enableScrollWheelZoom(true);
		var that = this;
		var zIndex;
		this.map_.addEventListener("tilesloaded",function(){
			$('.anchorBL').hide();
			var baiduClustMarker = $('.baidu-clustMarker');
			if(that.map_.getZoom()<=that.markerClustererClickZoom){
				baiduClustMarker.hide();
			}else{
				baiduClustMarker.show();
				$.each(baiduClustMarker,function(i,obj){
					var self = $(obj);
					self.off('mouseenter').unbind('mouseleave');
					self.hover(function(){
						zIndex = $(this).parent().css('z-index');
						$(this).parent().css('z-index',100);
					},function(){
						$(this).parent().css('z-index',zIndex);
					});
				});
			}
		});
	};
	//初始化标志物
	this.initMark = function(){
		var markerData = this.markerCtrl_.markerData;
		var that = this;
		$.each(markerData,function(i,obj){
			
			var point = new BMap.Point(obj.longitude,obj.latitude);
			//使用自定义图标
			if(that.markerCtrl_.customMarkerFlag){
				var label = new BMap.Label();
		        label.setStyle(that.markerCtrl_.customMarkerStyle||{border:'none',padding:0});
		        var content = '<div class="baidu-clustMarker"><a class="baidu-clustMarker-a" data-id="'+obj.id+'">'
		        	+obj.text+'</a>'+
		        				'<div class="baidu-clustMarker-divIcon"></div></div>';
		        label.setContent(content);
		        label.setPosition(point);
		        
		        if(that.markerCtrl_.markClickCallBack){
		        	label.addEventListener('click',function(event){
		        		that.markerCtrl_.markClickCallBack(event);
		        	});
		        }
		        
		        that.map_.addOverlay(label);        // 将标注添加到地图中
			}else{
				var marker = new BMap.Marker(point);
				that.map_.addOverlay(marker);         // 将标注添加到地图中
				that.overlays.push(marker);
				//使用官方定义marker图标
				var openInfoWindow;
				//拖动mark 给定监听事件
				if(that.markerCtrl_.markDraggable){
					marker.enableDragging();
					marker.addEventListener("dragend", function (e) {
						if(that.HomeControl_.marker&&that.HomeControl_.marker.dragendCallback){
							that.HomeControl_.marker.dragendCallback(e);
						}
					});
				}
				var opts = {
						width : 20,     // 信息窗口宽度
						height: 20,     // 信息窗口高度
						enableMessage:true//设置允许信息窗发送短息
				};
				var infoWindow = new BMap.InfoWindow(obj.infoWindowText||'',obj.opts||opts);  // 创建信息窗口对象
				//对marker进行监听
				if(that.markerCtrl_.markListenerFlag){
					marker.addEventListener("click", function(){
						openInfoWindow = that.map_.openInfoWindow(infoWindow,point); //开启信息窗口
					});
				}
			}
		});
		//设置聚合的最小级别
		$.each(this.markerCtrl_.markerClustererGroup,function(i,obj){
			if(i==0||that.markerClustererClickZoom<obj.minZoom){
				that.markerClustererClickZoom = obj.minZoom;
			}
		});
		//是否对聚合对象进行监听
		if(this.markerCtrl_.markerClustererFlag){
			// //最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
			var markerClusterer = new BMapLib.MarkerClusterer(this.map_, {
				markers : this.overlays,
				styles : [ {
					url : 'resource/images/map/redMin.png',
					hoverUrl:'resource/images/map/green.png',
					size : new BMap.Size(25, 25),
					backgroundColor : '#E64B4E',
					text : this.markerCtrl_.textBegin||'',
					textEnd:this.markerCtrl_.textEnd||'',
					markerClustererClickZoom:this.markerClustererClickZoom,
					markerClustererGroup:this.markerCtrl_.markerClustererGroup,
					markerClustererDefaultZoom:this.markerCtrl_.markerClustererDefaultZoom||10,
					customMarkerFlag:this.markerCtrl_.customMarkerFlag||false//是否使用自定义图标
				} ]
			});
		}
	};
	/**
	 * 百度地图工具控件
	 * @param map
	 */
	this.initControlUtils = function(HomeControlParam){
		var that = this;
		// 百度地图API功能
		// 定义一个控件类,即function
		function ZoomControl(){
		  // 默认停靠位置和偏移量
		  this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
		  this.defaultOffset = new BMap.Size(10, 10); // 距离左上角位置
		}

		// 通过JavaScript的prototype属性继承于BMap.Control
		ZoomControl.prototype = new BMap.Control();

		// 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
		// 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
		ZoomControl.prototype.initialize = function(){
		  // 创建一个工具
		  var div = document.createElement("div");
		  //在地图中增加工具  拖拽
		  that.HomeControl(div,{drawingtype:'hander',title:getText("#js_map_hander"),'clazz':'BMapLib_box BMapLib_hander',
			  							id:'bMapLib_hander',clickBack:that.clickHander});
		  //增加画点工具
		  if(HomeControlParam&&HomeControlParam.marker){
			  that.HomeControl(div,{drawingtype:'marker',title:getText("#js_map_markerSite"),'clazz':'BMapLib_box BMapLib_marker',
				  						id:'bMapLib_marker',clickBack:that.clickMarker});
		  }
		  //增加移除工具
		  if(HomeControlParam&&HomeControlParam.remove){
			  that.HomeControl(div,{drawingtype:'remove',title:getText("#js_map_removeSite"),'clazz':'BMapLib_box BMapLib_remove',
				  						id:'bMapLib_remove',clickBack:that.clickRemove});
		  }
		  div.setAttribute("class", "BMapLib_Drawing_panel");
		  // 设置样式
		  // 添加DOM元素到地图中
		  that.map_.getContainer().appendChild(div);
		  // 将DOM元素返回
		  return div;
		}
		// 创建控件
		var myZoomCtrl = new ZoomControl();
		// 添加到地图当中
		this.map_.addControl(myZoomCtrl);
	};
	//工具参数对象
	this.HomeControl = function(controlDiv,param) {
		var controlUI = document.createElement('a');
			controlUI.setAttribute("drawingtype",param.drawingtype);
			controlUI.setAttribute("title",param.title);
			controlUI.setAttribute("class",param.clazz);
			controlUI.setAttribute("id",param.id);
			controlUI.onclick = param.clickBack;
			controlDiv.appendChild(controlUI);
	};
	//单击拖动按钮
	this.clickHander = function(){
		$BaiduMap.map_.setDefaultCursor("grab");  
		if($BaiduMap.HomeControlMarkClick){
			$BaiduMap.map_.removeEventListener('click',$BaiduMap.HomeControlMarkClick);
		}
		$('#bMapLib_marker').removeClass('marker_select');
		$('#bMapLib_remove').removeClass('remove_select');
		var self = $(this);
		if(!self.hasClass('hander_select')){
			self.addClass('hander_select');
		}
		if($BaiduMap.HomeControl_&&$BaiduMap.HomeControl_.hander&&$BaiduMap.HomeControl_.hander.callback){
			$BaiduMap.HomeControl_.hander.callback();
		}
	};
	//单击标记按钮
	this.clickMarker = function(){
		//是否只能存在一个标记
		if($BaiduMap.HomeControl_.singleFlag){
			if($BaiduMap.overlays&&$BaiduMap.overlays.length==0){
				$BaiduMap.map_.setDefaultCursor("crosshair");
//				$BaiduMap.map_.setDefaultCursor("url('resource/images/map/redMin.png'),auto;");
				//变电站只有一个,强制性触发
				$('#bMapLib_remove').removeClass('remove_select');
				$('#bMapLib_hander').removeClass('hander_select');
				var self = $(this);
				if(!self.hasClass('marker_select')){
					self.addClass('marker_select');
				}
				$BaiduMap.click_lis.HomeCtrlClickLis = $BaiduMap.map_.addEventListener("click", $BaiduMap.HomeControlMarkClick);;
			}else{
				//弹出错误信息
				openMsg(getText('#'+$BaiduMap.HomeControl_.marker.msgId));
			}
		}else{
			//新增多个marker信息
		}
	};
	//单击移除按钮
	this.clickRemove = function(e){
		$BaiduMap.map_.setDefaultCursor("grab"); 
		if ($BaiduMap.overlays&&$BaiduMap.overlays.length>0) {
			$BaiduMap.map_.clearOverlays();
			$BaiduMap.overlays = [];
			if($BaiduMap.HomeControl_&&$BaiduMap.HomeControl_.remove&&$BaiduMap.HomeControl_.remove.callback){
				$BaiduMap.HomeControl_.remove.callback(e);
			}
			//不清空省市县镇数据
			/*$("input[name=province],input[name=city],input[name=county],input[name=town]").val('');
			$("#province,#city,#county,#town").val('0').trigger("change");*/
		}else{
			openMsg(getText('#js_map_removePower'));
		}
	};
	//点击工具标记的监听事件
	this.HomeControlMarkClick = function(event){
		var point =   event.point;//准备设置地图中心点 new google.maps.LatLng(event.latLng.lat(),event.latLng.lng());
		var marker = new BMap.Marker(point);// 创建标注
		$BaiduMap.map_.addOverlay(marker);         // 将标注添加到地图中
		marker.enableDragging();
		$BaiduMap.overlays[0] = marker;
		marker.addEventListener("dragend", function (e) {
			$BaiduMap.overlays[0] = marker;
			if($BaiduMap.HomeControl_&&$BaiduMap.HomeControl_.marker&&$BaiduMap.HomeControl_.marker.dragendCallback){
				$BaiduMap.HomeControl_.marker.dragendCallback(e);
			}
		});
		if($BaiduMap.HomeControl_&&$BaiduMap.HomeControl_.marker&&$BaiduMap.HomeControl_.marker.callback){
			$BaiduMap.HomeControl_.marker.callback(event);
		}
		$BaiduMap.map_.removeEventListener('click',$BaiduMap.HomeControlMarkClick);
		$BaiduMap.map_.setDefaultCursor("grab"); 
		$('#bMapLib_hander').trigger('click');
	};
	this.getAddressByPoint = function(latitude,longitude,key,callback){
		$.ajax({
			url:"https://api.map.baidu.com/geocoder/v2/?output=json&pois=1&ak="+key+"&location="+latitude+","+longitude,
			async:true,
			dataType : "jsonp",
			success:function(data){
				var param = {};
				if(data.result){
					param.result = data.result;
					param.addressComponent = param.result.addressComponent;
					param.nation = param.addressComponent.country;
					if(param.addressComponent.province==param.addressComponent.city){
						param.province = param.addressComponent.province;
						param.city = param.addressComponent.district;
						//param.county = param.addressComponent.district;
					}else{
						param.province = param.addressComponent.province;
						param.city = param.addressComponent.city;
						param.county = param.addressComponent.district;
					}
				}
				if(param){
					callback(param);
				}
			},
			error:function(data){
				 
			}
		});
	};
	
	//初始化方法
	this.init = function(){
		this.initBaiduMap();
		if(this.markerCtrl_){
			this.initMark();
		}
		if(this.HomeControl_){
			this.initControlUtils(this.HomeControl_);
		}
	};
	//定位方法
	this.PanTogeolocation = function(){
		var geolocation = new BMap.Geolocation();
		var that = this;
		//获取当前电脑所在地理位置
		geolocation.getCurrentPosition(function(r){
			if(this.getStatus() == BMAP_STATUS_SUCCESS && that.options_.geolocationFlag){
				that.map_.panTo(r.point); 
			}else{
			}
		},{enableHighAccuracy: true});
	};
	
	//IP定位获取定位点
	this.getLocalCityPoint = function(){
		var localCity = new BMap.LocalCity();
		var that = this;
		localCity.get(localCallback);
		
		//定位回调函数
		function localCallback(result){
			that.map_.centerAndZoom(result.center,that.options_.zoom||6);
		}
	};
	
	var mapDivFlag = document.getElementById(this.options_.mapId);
	if(mapDivFlag){
		this.init();
	}
};